package com.thread.threadfirst.RedisLock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * redis实现分布式锁
 */
public class RedisLock {
    private StringRedisTemplate stringRedisTemplate;

    public String deductStack() {
        String key = "lockKey";
        String clientId = UUID.randomUUID().toString();
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, clientId, 10, TimeUnit.SECONDS);   //那么此处的时间应该怎么掌握呢
//        Boolean result=stringRedisTemplate.opsForValue().setIfAbsent(key,clientId);
//        stringRedisTemplate.expire(key,10,TimeUnit.SECONDS);      //注意：如果上面的set和此处的expire是分开写的，则可能会执行完上句还没执行此句服务器就宕机了，所以要合成一句。
        if (!result) {
            return "error";
        }
        try {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("stock", stock + "");
                System.out.println("扣减库存成功！剩余库存" + stock + "");
            } else {
                System.out.println("库存不足");
            }
        } finally {
            if (stringRedisTemplate.opsForValue().get(key).equals(clientId)) {
                //释放锁
                stringRedisTemplate.delete(key);
            }
        }
        return "end";
    }
}
